<template>
  <template v-for="(cMenu, index) in menu || []" :key="index">
    <!-- 有子菜单 -->
    <q-expansion-item v-if="cMenu.children" :key="index" :dense="isDense" :group="group(initLevel)"
                      :header-inset-level="initLevel" :icon="icon(cMenu.meta, 'storage')" :label="menuName(cMenu.meta)"
                      :model-value="baseOpen(cMenu.meta)">
      <menu-item :init-level="initLevel + 0.25" :menu="cMenu.children" :open-menu="openMenu"></menu-item>
    </q-expansion-item>
    <!-- 没有子菜单 -->
    <q-item v-else :active="isActive(cMenu.name)" :dense="isDense" :disable="setDisabled(cMenu.meta)"
            :inset-level="initLevel" active-class="text-primary menu-cls-active" clickable
            @click="skipPath(cMenu.name)">
      <q-item-section avatar class="col-auto">
        <q-icon :name="icon(cMenu.meta, 'insert_chart')" />
      </q-item-section>
      <q-item-section>{{ menuName(cMenu.meta) }}</q-item-section>
      <q-item-section v-if="isActive(cMenu.name)" side>
        <q-icon class="active-menu-icon" name="double_arrow" size="1rem"></q-icon>
      </q-item-section>
    </q-item>
  </template>
</template>

<script setup>
import { toI18nName } from 'boot/i18n'
import { computed, inject, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const props = defineProps({
  menu: Array, initLevel: Number, openMenu: String
})

const route = useRoute()
const router = useRouter()
const handleLoad = inject('handleLoad')
const isDense = inject('isDense', true)
const group = computed(() => level => `${level}-group`)
const isActive = computed(() => name => name === route.name)
const icon = computed(() => (meta = {}, icon) => meta.menuIcon || icon)
const setDisabled = computed(() => (meta = {}) => meta.menuType === 'F')
const openMenuIds = computed(() => (props.openMenu || '').split(','))
const baseOpen = computed(() => (meta = {}) => openMenuIds.value.includes(meta.menuId))

const menuName = (meta = {}) => meta[toI18nName('menuZhCn')] || meta.title

const skipPath = name => {
  if (name === route.name) return
  handleLoad(true)
  nextTick(async () => {
    await router.push({ name })
    handleLoad(false)
  })
}

</script>